package spe.ui.editor;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartFactory;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.ui.parts.ContentOutlinePage;
import org.eclipse.gef.ui.parts.TreeViewer;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.IPageLayout;

public abstract class SPEOutlineViewer extends ContentOutlinePage
{
	private static final String ID = IPageLayout.ID_OUTLINE;
	
	private SPEEditor editor;
	private Control treeview;
	
	public SPEOutlineViewer(SPEEditor editor) 
	{
		super(new TreeViewer());
		editor.getSelectionSychronizer().addViewer(getViewer());
		this.editor = editor;
	}
	
	protected abstract void initEditPartFactory();
	
	public void createControl(Composite parent) 
	{
		createTreeview(parent);
	}
	
	private void createTreeview(Composite parent) {
		treeview = getViewer().createControl(parent);
		GraphicalViewerContextMenuProvider provider = new GraphicalViewerContextMenuProvider(getViewer(), editor.getActionRegistry());
		getViewer().setContextMenu(provider);
		getSite().registerContextMenu("spe.outline.context", provider, getViewer());
		treeview.addMouseListener(new MouseAdapter() {
			public void mouseDoubleClick(MouseEvent e) {
				handleDoubleClick();				
			}
		});
		getSite().setSelectionProvider(getViewer());
		getViewer().setEditDomain(editor.getGraphicalViewer().getEditDomain());
		initEditPartFactory(); 
		setContents(editor.getDiagram());
	}
	
	private void handleDoubleClick()
	{
		EditPart editPart = (EditPart)getViewer().getSelectedEditParts().get(0);
		Request openPropertiesRequest = new Request(RequestConstants.REQ_OPEN);
		editPart.performRequest(openPropertiesRequest);
	}

//	public CommandStack getCommandStack() {
//		return editor.getCommandStack();
//	}
//	
	public SPEEditor getEditor() {
		return editor;
	}

	@Override
	public Control getControl() {
		return treeview;
	}

	@Override
	public void setFocus() {
		if (getControl() != null)
			getControl().setFocus();
	}

	public void setContents(Object contents) {
		getViewer().setContents(contents);
	}
	
	protected void setEditPartFactory(EditPartFactory factory) {
		getViewer().setEditPartFactory(factory);
	}
	
	public String getId()
	{
		return ID;
	}
}
